package util

import (
	"github.com/gogf/gf/os/glog"

	"fmt"
	"time"

	"github.com/360EntSecGroup-Skylar/excelize"
	"github.com/zhwei820/excelclaim/excel"
)

// ReadExcelRows ReadExcelRows
func ReadExcelRows(fp string) (res [][]string) {
	// fp filepath
	res = make([][]string, 0)
	f, err := excelize.OpenFile(fp)

	if err != nil {
		glog.Error(err)
		return
	}
	sheets := f.GetSheetMap()

	if len(sheets) == 0 {
		glog.Error(err)
		return
	}

	rows := f.GetRows(sheets[1]) // 取第一页,
	for _, row := range rows {
		rowData := []string{}
		for _, colCell := range row {
			rowData = append(rowData, colCell)
		}
		res = append(res, rowData)
	}
	return
}

// WriteExcelRows WriteExcelRows
func WriteExcelRows(fp string, headerMap map[string]string, headerKeys []string, data []map[string]string) {
	xlsx := excelize.NewFile()

	t1 := time.Now()

	t2 := time.Now()
	fmt.Println("dt", t2.Sub(t1).Seconds())
	t1 = time.Now()

	sheet1(xlsx, data, headerMap, headerKeys)
	// sheet2(xlsx)
	t2 = time.Now()
	fmt.Println("dt2", t2.Sub(t1).Seconds())

	err := xlsx.SaveAs(fp)
	if err != nil {
		fmt.Println(err)
		return
	}
}

// sheet1
// headerMap: [{key:xx, value:yy}]
// data: [{key1:val1, key2:val2}]
func sheet1(xlsx *excelize.File, data []map[string]string, headerMap map[string]string, headerKeys []string) {
	sheet := excel.NewSheet(xlsx, "sheet1", len(headerMap), 24)

	header := []string{}
	for _, v := range headerKeys {
		header = append(header, headerMap[v])
	}
	sheet.WriteRow(header...)

	for _, item := range data {
		tmp := []string{}
		for _, v := range headerKeys {
			tmp = append(tmp, item[v])
		}
		sheet.WriteRow(tmp...)
	}
}
